<template>
    <div>
        <div>ollamaDs</div>
        <div>{{ textData }}</div>
    </div>
</template>

<script setup name="ollamaDs">
import { onMounted, reactive, ref } from 'vue'
let textData = ref('')
onMounted(() => {
    return
    const requestOptions = {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Accept': '*/*'
        },
        body: JSON.stringify({
            model: "deepseek-r1:7b",
            prompt: "用JavaScript写一个快速排序函数",
            stream: true  // 保持流式传输
        })
    };

    fetch("http://localhost:11434/api/generate", requestOptions)
        .then(response => {
            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            let result = '';

            function readChunk() {
                return reader.read().then(({ value, done }) => {
                    if (done) {
                        console.log("完整响应:", result);
                        return;
                    }

                    // 解码并处理数据块
                    const chunk = decoder.decode(value);
                    try {
                        const json = JSON.parse(chunk);
                        if (json.response) {
                            result += json.response; // 拼接响应片段
                            //   console.log("收到片段:", json.response);
                            textData.value = `${textData.value}${json.response}`
                        }
                    } catch (e) {
                        console.error("解析错误:", e);
                    }

                    return readChunk(); // 继续读取下一块
                });
            }

            return readChunk();
        })
        .catch(error => console.error('请求失败:', error));
});
</script>
<style scoped lang="scss"></style>